package cn.aspect.util;

import cn.aspect.annotation.Desensitization;
import cn.aspect.annotation.SnowflakeId;
import cn.aspect.enums.DESENSITIZATION_TYPE;
import cn.aspect.exception.AnnotationParsingException;
import cn.hutool.core.util.DesensitizedUtil;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class AnnotationUtil {

    public static <T> void handleSnowflakeId(T clazz) throws Exception {
        if (null == clazz) {
            return;
        }
        // 获取该类所有的字段
        Field[] fields = clazz.getClass().getDeclaredFields();
        // 遍历该类所有的字段
        for (Field field : fields) {
            field.setAccessible(true);
            // 通过字段获取指定的注解
            if (field.isAnnotationPresent(SnowflakeId.class)) {
                // 只支持Long数据类型
                if (!(field.getType() == Long.class || field.getType() == long.class)) {
                    throw new AnnotationParsingException("赋值@SnowflakeId字段类型不兼容,请使用Long字段类型");
                }
                // 如果字段上有注解,并且该字段没值则向该字段赋值
                if ((null == field.get(clazz)) ||
                        (field.getType() == long.class && 0l == (long) field.get(clazz))
                        || (field.getType() == Long.class && 0L == (Long) field.get(clazz))) {
                    // 获取注解上的value
                    SnowflakeId annotation = field.getAnnotation(SnowflakeId.class);
                    field.set(clazz, annotation.value() != 0 ? annotation.value() : IdUtils.getSnowflakeId());
                }
            }
        }
    }

    public static <T> void handleDesensitization(T clazz) throws Exception {
        if (null == clazz) {
            return;
        }
        // 获取该类所有的字段
        Field[] fields = clazz.getClass().getDeclaredFields();
        // 遍历该类所有的字段
        for (Field field : fields) {
            field.setAccessible(true);
            // 通过字段获取指定的注解
            if (field.isAnnotationPresent(Desensitization.class)) {
                // 只支持String数据类型
                if (field.getType() != String.class) {
                    throw new AnnotationParsingException("赋值@Desensitization字段类型不兼容,请使用String字段类型");
                }
                // 获取注解信息
                Desensitization annotation = field.getAnnotation(Desensitization.class);
                String value = (String) field.get(clazz);
                if (value == null || value.trim().length() == 0 || annotation.type().getCode().equals(DESENSITIZATION_TYPE.NONE.getCode())) {
                    continue;
                }
                //  脱敏处理
                String result = annotation.type().getApply().apply(value.trim());
                if (result.length() > 0) {
                    field.set(clazz, annotation.type().getApply().apply(value));
                }
            }
        }
    }

}
